package com.kaili.basic.service.impl;

/**
 * Created by xxx on 2019-03-07.
 */

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.mapper.CustomerMapper;
import com.kaili.basic.mapper.OutboundApplicationMapper;
import com.kaili.basic.mapper.OutboundProductMapper;
import com.kaili.basic.mapper.SupplierMapper;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.*;
import com.kaili.basic.service.OutboundApplicationService;
import com.kaili.common.util.LoginDetailUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xxx
 * @Copyright: Copyright (c) 2017
 * @Company: 杭州凯立通信有限公司
 */
@Service
public class OutboundApplicationServiceImpl implements OutboundApplicationService {
    @Autowired
    OutboundApplicationMapper outboundApplicationMapper;
    @Autowired
    OutboundProductMapper outboundProductMapper;
    @Autowired
    SupplierMapper supplierMapper;
    @Autowired
    CustomerMapper customerMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int addOutboundApplication(OutboundApplicationAddDto outboundApplicationAddDto) {
        OutboundApplication outboundApplication = new OutboundApplication();
        BeanUtils.copyProperties(outboundApplicationAddDto, outboundApplication);
        Long applyId = Long.parseLong(outboundApplication.getRequestCode());
        /*Long applyId = outboundApplicationMapper.getMaxApplyId();
        applyId = applyId + 1L;
        outboundApplication.setRequestCode(StringUtils.leftPad(applyId.toString(), 6, "0"));*/
        outboundApplication.setCreateBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        outboundApplication.setApplyId(applyId);
        Supplier supplier=supplierMapper.querySupplierById(outboundApplication.getSupplierId());
        if(supplier!=null){
            outboundApplication.setSupplierCode(supplier.getSupplierCode());
            outboundApplication.setSupplierName(supplier.getSupplierName());
        }
        Customer customer=customerMapper.queryCustomerById(outboundApplication.getCustomerId());
        if(customer!=null){
            outboundApplication.setCustomerCode(customer.getCustomerCode());
            outboundApplication.setCustomerName(customer.getCustomerName());
        }
        outboundApplicationMapper.addOutboundApplication(outboundApplication);
        int order=1;
        for (OutboundProductDto outboundProductDto : outboundApplicationAddDto.getOutboundProductList()) {
            OutboundProduct outboundProduct=new OutboundProduct();
            BeanUtils.copyProperties(outboundProductDto, outboundProduct);
            outboundProduct.setApplyId(applyId);
            outboundProduct.setCreateBy(outboundApplication.getCreateBy());
            outboundProduct.setOutboundOrder(order);
            outboundProductMapper.addOutboundProduct(outboundProduct);
            order++;
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int deleteOutboundApplication(OutboundApplication outboundApplication) {
        outboundApplicationMapper.deleteOutboundApplication(outboundApplication);
        OutboundProduct outboundProduct =new OutboundProduct();
        outboundProduct.setApplyId(outboundApplication.getApplyId());
        outboundProduct.setModifyBy(outboundApplication.getModifyBy());
        outboundProductMapper.deleteOutboundProduct(outboundProduct);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int deleteOutboundApplications(BusinessOperationDeleteDto deleteDto) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("modifyBy",LoginDetailUtils.getCurrentEmployeeId().longValue());
        if(deleteDto.getMainIds()!=null&&deleteDto.getMainIds().length>0){
            map.put("applyIds",deleteDto.getMainIds());
            outboundApplicationMapper.deleteOutboundApplications(map);
        }
        if(deleteDto.getSonIds()!=null&&deleteDto.getSonIds().length>0) {
            map.put("ids", deleteDto.getSonIds());
            outboundProductMapper.deleteOutboundProductList(map);
            for(Long id:deleteDto.getSonIds()){
                OutboundProduct outboundProduct=outboundProductMapper.getOutboundProductByIdAll(id);
                if(outboundProduct!=null){
                    //查询删除子项的主表id下总出库数量和总数量的差来判断出库的状态
                    Integer differQuantity=outboundApplicationMapper.getDifferQuantity(outboundProduct.getApplyId());
                    if(differQuantity!=null) {
                        OutboundApplication outboundApplicationMy = new OutboundApplication();
                        outboundApplicationMy.setApplyId(outboundProduct.getApplyId());
                        outboundApplicationMy.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
                        if (differQuantity.intValue() == 0) {
                            outboundApplicationMy.setOrderStatus(5);
                        } else {
                            outboundApplicationMy.setOrderStatus(4);
                        }
                        outboundApplicationMapper.updateOutboundApplication(outboundApplicationMy);
                    }
                }
            }
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateOutboundApplication(OutboundApplicationUpdateDto outboundApplicationUpdateDto) {
        OutboundApplication outboundApplication = new OutboundApplication();
        BeanUtils.copyProperties(outboundApplicationUpdateDto, outboundApplication);
        outboundApplication.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        Supplier supplier=supplierMapper.querySupplierById(outboundApplication.getSupplierId());
        if(supplier!=null){
            outboundApplication.setSupplierCode(supplier.getSupplierCode());
            outboundApplication.setSupplierName(supplier.getSupplierName());
        }
        Customer customer=customerMapper.queryCustomerById(outboundApplication.getCustomerId());
        if(customer!=null){
            outboundApplication.setCustomerCode(customer.getCustomerCode());
            outboundApplication.setCustomerName(customer.getCustomerName());
        }
        outboundApplicationMapper.updateOutboundApplication(outboundApplication);
        //先删除该申请下的产品，因为不确定是否有删除的子项产品，之后在后面的修改中恢复正常状态
        OutboundProduct outboundProductMy=new OutboundProduct();
        outboundProductMy.setApplyId(outboundApplication.getApplyId());
        outboundProductMy.setModifyBy(outboundApplication.getModifyBy());
        outboundProductMapper.deleteByApplyId(outboundProductMy);
        int order=1;
        for (OutboundProductDto outboundProductDto : outboundApplicationUpdateDto.getOutboundProductList()) {
            OutboundProduct outboundProduct=new OutboundProduct();
            BeanUtils.copyProperties(outboundProductDto, outboundProduct);
            outboundProduct.setApplyId(outboundApplication.getApplyId());
            outboundProduct.setOutboundOrder(order);
            //没有子项主键id的做新增，有的则修改
            if(outboundProduct.getId()==null||outboundProduct.getId().longValue()==0L){
                outboundProduct.setCreateBy(outboundApplication.getModifyBy());
                outboundProductMapper.addOutboundProduct(outboundProduct);
            }else{
                //OutboundProduct outboundProductMy=outboundProductMapper.getOutboundProductById(outboundProduct.getId());
                //outboundProduct.setResidueQuantity(outboundProduct.getQuantity()-outboundProductMy.getSelectSum()-outboundProductMy.getSalesReturnQuantity());
                outboundProduct.setResidueQuantity(outboundProduct.getQuantity());
                outboundProduct.setResidueVolume(outboundProduct.getOutVolume());
                outboundProduct.setResidueWeight(outboundProduct.getOutWeight());
                outboundProduct.setModifyBy(outboundApplication.getModifyBy());
                //恢复正常状态
                outboundProduct.setRdStatus(1);
                outboundProductMapper.updateOutboundProduct(outboundProduct);
            }
            order++;
        }
        return 1;
    }

    @Override
    public Page<OutboundApplication> queryOutboundApplication(Page<OutboundApplication> page, OutboundApplicationQueryDto outboundApplication) {
        List<OutboundApplication> outboundApplications = outboundApplicationMapper.queryOutboundApplication(page,outboundApplication);
        return page.setRecords(outboundApplications);
    }

    @Override
    public OutboundApplication queryOutboundApplicationById(Long applyId) {
        return outboundApplicationMapper.queryOutboundApplicationById(applyId);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateAffirmOrCancel(OutboundApplication outboundApplication) {
        outboundApplicationMapper.updateOutboundApplication(outboundApplication);
        OutboundProduct outboundProduct = new OutboundProduct();
        outboundProduct.setApplyId(outboundApplication.getApplyId());
        outboundProduct.setModifyBy(outboundApplication.getModifyBy());
        outboundProduct.setOrderStatus(outboundApplication.getOrderStatus());
        outboundProductMapper.updateConfirmToCancel(outboundProduct);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateOrderOutbound(List<BaseOutStoreDetailAddDTO> detailList, String requestCode) {
        Long employeeId=LoginDetailUtils.getCurrentEmployeeId().longValue();
        for(BaseOutStoreDetailAddDTO detail:detailList){
            OutboundProduct outboundProduct=outboundProductMapper.getOutboundProductById(detail.getApplyProductId());
            if(outboundProduct==null){
                continue;
            }
            //出库操作后修改出库产品信息(数量，重量，体积等)
            OutboundProduct outboundProductMy=new OutboundProduct();
            outboundProductMy.setId(detail.getApplyProductId());
            outboundProductMy.setSelectSum(outboundProduct.getSelectSum()+Integer.parseInt(String.valueOf(detail.getAmount())));
            outboundProductMy.setResidueQuantity(outboundProduct.getResidueQuantity()-Integer.parseInt(String.valueOf(detail.getAmount())));
            outboundProductMy.setResidueWeight(outboundProduct.getResidueWeight()-detail.getWeight());
            outboundProductMy.setResidueVolume(outboundProduct.getResidueVolume()-detail.getVolume());
            //如果总的出库数量与要出库的数量相同则全部出库状态
            if(outboundProductMy.getSelectSum().intValue()==outboundProduct.getQuantity().intValue()){
                outboundProductMy.setOrderStatus(5);
            }else{
                outboundProductMy.setOrderStatus(4);
            }
            outboundProductMy.setModifyBy(employeeId);
            outboundProductMapper.updateOutboundProduct(outboundProductMy);
        }
        //修改出库主表的状态信息
        OutboundApplication outboundApplication=outboundApplicationMapper.queryOutboundApplicationByNo(requestCode);
        if(outboundApplication!=null){
            //查询主表下总出库数量和总数量的差来判断出库的状态
            Integer differQuantity=outboundApplicationMapper.getDifferQuantity(outboundApplication.getApplyId());
            if(differQuantity!=null) {
                OutboundApplication outboundApplicationMy = new OutboundApplication();
                outboundApplicationMy.setApplyId(outboundApplication.getApplyId());
                outboundApplicationMy.setModifyBy(employeeId);
                if (differQuantity.intValue() == 0) {
                    outboundApplicationMy.setOrderStatus(5);
                } else {
                    outboundApplicationMy.setOrderStatus(4);
                }
                outboundApplicationMapper.updateOutboundApplication(outboundApplicationMy);
            }
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateOrderOutboundByAudit(List<BaseOutStoreDetailEntity> detailList) {
        for (BaseOutStoreDetailEntity detail:detailList) {
            //出库审核通过后修改出库产品可退货的信息(数量，重量，体积等)
            OutboundProduct outboundProduct=outboundProductMapper.getOutboundProductById(detail.getApplyProductId());
            if(outboundProduct==null){
                continue;
            }
            OutboundProduct outboundProductMy=new OutboundProduct();
            outboundProductMy.setId(detail.getApplyProductId());
            outboundProductMy.setActualSelectQuantity(outboundProduct.getActualSelectQuantity()+Integer.parseInt(String.valueOf(detail.getAmount())));
            outboundProductMy.setReturnQuantity(outboundProduct.getReturnQuantity()+Integer.parseInt(String.valueOf(detail.getAmount())));
            outboundProductMy.setReturnWeight(outboundProduct.getReturnWeight()+detail.getWeight());
            outboundProductMy.setReturnVolume(outboundProduct.getReturnVolume()+detail.getVolume());
            outboundProductMy.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
            outboundProductMapper.updateOutboundProduct(outboundProductMy);
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateOrderOutboundReturn(List<OutboundReturnProductDto> returnProductList, String requestCode) {
        Long employeeId=LoginDetailUtils.getCurrentEmployeeId().longValue();
        for(OutboundReturnProductDto returnProduct:returnProductList){
            OutboundProduct outboundProduct=outboundProductMapper.getOutboundProductById(returnProduct.getOutProductId());
            if(outboundProduct==null){
                continue;
            }
            //退货操作后修改出库产品信息(数量，重量，体积等)
            OutboundProduct outboundProductMy=new OutboundProduct();
            outboundProductMy.setId(returnProduct.getOutProductId());
            outboundProductMy.setSalesReturnQuantity(outboundProduct.getSalesReturnQuantity()+returnProduct.getQuantity());
            outboundProductMy.setReturnQuantity(outboundProduct.getReturnQuantity()-returnProduct.getQuantity());
            outboundProductMy.setReturnWeight(outboundProduct.getReturnWeight()-returnProduct.getWeight());
            outboundProductMy.setReturnVolume(outboundProduct.getReturnVolume()-returnProduct.getVolume());
            outboundProductMy.setModifyBy(employeeId);
            outboundProductMapper.updateOutboundProduct(outboundProductMy);
        }
        //修改出库申请主表的退货状态信息
        OutboundApplication outboundApplication=outboundApplicationMapper.queryOutboundApplicationByNo(requestCode);
        if(outboundApplication!=null){
            OutboundApplication outboundApplicationMy = new OutboundApplication();
            outboundApplicationMy.setApplyId(outboundApplication.getApplyId());
            outboundApplicationMy.setModifyBy(employeeId);
            outboundApplicationMy.setSalesReturnStatus(1);
            outboundApplicationMapper.updateOutboundApplication(outboundApplicationMy);
        }
        return 1;
    }

    @Override
    public Long getMaxApplyId() {
        return outboundApplicationMapper.getMaxApplyId();
    }

    @Override
    public Long queryWarehouseInventory(OutboundInventoryQueryDto outboundInventoryQueryDto) {
        return outboundApplicationMapper.queryWarehouseInventory(outboundInventoryQueryDto);
    }

    @Override
    public List<OutboundApplicationExport> queryOutboundApplicationExport(OutboundApplicationQueryDto outboundApplicationQueryDto) {
        return outboundApplicationMapper.queryOutboundApplicationExport(outboundApplicationQueryDto);
    }
}
